package main

import (
	"encoding/json"
	"fmt"
)

type Person struct {
	Name string `json:"name"`
	Age  int    `json:"-"`
}

func main() {
	p := Person{"John", 20}
	// 编码 json
	b, err := json.Marshal(p)
	if err != nil {
		fmt.Println("json err ", err)
	}
	fmt.Println(string(b))

	// 格式化输出
	b, err = json.MarshalIndent(p, "", "     ")
	if err != nil {
		fmt.Println("json err ", err)
	}
	fmt.Println(string(b))

	fmt.Println("---jsonByMap--")
	jsonByMap()
	fmt.Println("---unMarshal--")
	unMarshal()
	fmt.Println("---unMarshalInterface--")
	unMarshalInterface()
}

func jsonByMap() {
	student := make(map[string]interface{})
	student["name"] = "John"
	student["age"] = 20
	student["married"] = true
	fmt.Println(student)
	marshal, err := json.Marshal(student)
	if err != nil {
		return
	}
	fmt.Println(string(marshal))
}

func unMarshal() {
	b := []byte(`{"name":"John","age":20}`)
	var p Person
	err := json.Unmarshal(b, &p)
	if err != nil {
		return

	}
	fmt.Println(p)
}

func unMarshalInterface() {
	// 假数据
	// int和float64都当float64
	b := []byte(`{"age":1.3,"name":"5lmh.com","marry":false}`)
	// 声明接口
	var i interface{}
	err := json.Unmarshal(b, &i)
	if err != nil {
		return
	}
	fmt.Println(i)

	//判断类型
	m := i.(map[string]interface{})
	for k, v := range m {
		fmt.Println(k, v)
		switch vv := v.(type) {
		case string:
			fmt.Println(k, "是float64类型", vv)
		case float64:
			fmt.Println(k, "是string类型", vv)
		case bool:
			fmt.Println(vv)
		default:
		}
	}
}
